package com.hulbox.app;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ListActivity {
	private static final String TAG = "Myinstaller";
	
	private class MyAsyncTask extends AsyncTask<Void, Void, Void>
    {

        ProgressDialog mProgressDialog;
        @Override
        protected void onPostExecute(Void result) {
            mProgressDialog.dismiss();
        }

        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(MainActivity.this, "Loading...", "Data is Loading...");
        }

        protected boolean urlDownloadtoFile(String url, String filename) {
        	HttpClient http = new DefaultHttpClient();
        	HttpGet request = new HttpGet(url);
        	
        	try {
        	    HttpResponse response = http.execute(request);
        	    InputStream fileStream = response.getEntity().getContent();
        	    FileOutputStream output = openFileOutput(filename, MODE_WORLD_READABLE);

        	    byte[] buffer = new byte[1024];
        	    int len = 0;
        	    while ((len = fileStream.read(buffer)) > 0) {
        	        output.write(buffer, 0, len);
        	    }
        	    fileStream.close();
        	    output.close();
        	    return true;

        	} catch (ClientProtocolException e) {
        		//Toast.makeText( null , e.getMessage(), Toast.LENGTH_SHORT).show();
        	    e.printStackTrace();
        	} catch (IOException e) {
        		//Toast.makeText( null , e.getMessage(), Toast.LENGTH_SHORT).show();
        	    e.printStackTrace();
        	} catch (Exception e) {
        		e.printStackTrace();
        	}
        	
        	return false;
        }
        
        protected boolean getFileList() {
        	final String json_url = "http://pack.liking.co.kr/json/pack_list.json";
        	final String json_file = "app_list.json";
        	
        	boolean bSave = urlDownloadtoFile(json_url, json_file);
        	return bSave;
        }
        
        @Override
        protected Void doInBackground(Void... params) {
        	final String apk_url = "http://192.168.0.44/test/aaa.apk";
        	final String apk_name = "aaa.apk";

        	boolean bSave = urlDownloadtoFile(apk_url, apk_name);
        	if(bSave) {
	    	    Intent intent = new Intent(Intent.ACTION_VIEW);
	    	    intent.setDataAndType(Uri.fromFile(getFileStreamPath(apk_name)), 
	    	                       "application/vnd.android.package-archive");
	    	    startActivity(intent); 
        	} else {
        		Toast.makeText(getApplicationContext(), "apk 다운로드를 실패하였습니다.", Toast.LENGTH_SHORT).show();
        		// download failure
        	}
            return null;
        }
    }
	public ArrayList<HashMap<String, String>> items;

	@Override
	  protected void onListItemClick(ListView l, View v, int position, long id){
	   super.onListItemClick(l, v, position, id);
	   HashMap<String, String> o = items.get(position);
	   String appNum = o.get("appNum");
	   onLaunchTstore(appNum);
	}
	
	/*
	 * private class DoComplecatedJob extends AsyncTask<Params, Progress, Result> 
	 */
	private class MyAsyncTask2 extends AsyncTask<String, Void, Void>
    {
        ProgressDialog mProgressDialog;
        @Override
        protected void onPostExecute(Void result) {
            mProgressDialog.dismiss();
        	setItemAdapter(items);
       }

        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(MainActivity.this, "Loading...", "Data is Loading...");
        }

        protected boolean urlDownloadtoFile(String url, String filename) {
        	HttpClient http = new DefaultHttpClient();
        	HttpGet request = new HttpGet(url);
        	
        	try {
        	    HttpResponse response = http.execute(request);
        	    InputStream fileStream = response.getEntity().getContent();
        	    FileOutputStream output = openFileOutput(filename, MODE_WORLD_READABLE);

        	    byte[] buffer = new byte[1024];
        	    int len = 0;
        	    while ((len = fileStream.read(buffer)) > 0) {
        	        output.write(buffer, 0, len);
        	    }
        	    fileStream.close();
        	    output.close();
        	    return true;

        	} catch (ClientProtocolException e) {
        		//Toast.makeText( null , e.getMessage(), Toast.LENGTH_SHORT).show();
        	    e.printStackTrace();
        	} catch (IOException e) {
        		//Toast.makeText( null , e.getMessage(), Toast.LENGTH_SHORT).show();
        	    e.printStackTrace();
        	} catch (Exception e) {
        		e.printStackTrace();
        	}
        	
        	return false;
        }
        
        protected boolean getFileList() {
        	final String json_url = "http://pack.liking.co.kr/json/pack_list.json";
        	final String json_file = "app_list.json";
        	
        	boolean bSave = urlDownloadtoFile(json_url, json_file);
        	return bSave;
        }
        
        @Override
        protected Void doInBackground(String... params) {
        	final String json_url = "http://pack.liking.co.kr/json/pack_list.json";
        	final String json_file = "app_list.json";
        	MyJSON json = new MyJSON();
        	json.parent = MainActivity.this;
        	boolean bSave = json.parseJSON(json_url);
        	items = json.itemArray;
            return null;
        }
    }

	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        onMenu1();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    ItemAdapter m_adapter = null;
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch(item.getItemId()) {
    	case R.id.menu_1:
    		onMenu1();
    		return true;
    	case R.id.menu_2:
    		onMenu2();
    		return true;
    	case R.id.menu_3:
    		return true;
    	case R.id.menu_4:
    		return true;
    	}
    	return false;
    }
    
    private void onMenu1() {
    	onLaunchJSON();
	}

	private void onMenu2() {
	
	}

	/*
	 * Check package installation.
     * TStore: com.skt.skaf.A000Z00040
     */
	PackageManager pm = null;
	List<ApplicationInfo> appList = null;
    public boolean CheckPackage(String pkg_name) {
    	if(pm == null) {
    		pm = getPackageManager();
    	}
    	if(appList == null) {
        	appList = pm.getInstalledApplications( 0 );
    	}
    	ApplicationInfo app = null;
    	int nSize = appList.size();
    	for(int i = 0; i < nSize; i++) {
    		app = appList.get(i);
    		if(app.packageName.indexOf(pkg_name) != -1) {
    			return true;
    		}
    	}
    	return false;
    }
    /*
     * 0000017866 留�諛붽�寃�
     */
    public void onLaunchTstore(String app_id) {
    	Intent intent = new Intent();
    	intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    	intent.setClassName("com.skt.skaf.A000Z00040", "com.skt.skaf.A000Z00040.A000Z00040");
    	intent.setAction("COLLAB_ACTION");
    	intent.putExtra("com.skt.skaf.COL.URI", ("PRODUCT_VIEW/" + app_id + "/0").getBytes());
    	intent.putExtra("com.skt.skaf.COL_REQUESTER", "A000Z00040");
    	startActivity(intent);
    }
    
    /*
     * �낅뜲�댄듃 �댁뿭 �덈궡 �섏씠吏�줈 TStore �몄텧
     */
    public void onLaunchTstoreUpdate() {
    	String strMsg = "PRODUCT_UPDATE/0000264687/0";
    	Intent intent = new Intent();
    	intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    	intent.setClassName("com.skt.skaf.A000Z00040", "com.skt.skaf.A000Z00040.A000Z00040");
    	intent.setAction("COLLAB_ACTION");
    	intent.putExtra("com.skt.skaf.COL.URI", strMsg.getBytes());
    	intent.putExtra("com.skt.skaf.COL.REQUESTER", "A000Z00040");
    	startActivity(intent);
    }
    public void onClickInstall() {   	
    	new MyAsyncTask().execute();
    }
    
    public void onLaunchJSON() {
    	new MyAsyncTask2().execute();
 	
    }

    private class ItemAdapter extends ArrayAdapter<HashMap<String, String>> {

		private ArrayList<HashMap<String, String>> items;

		public ItemAdapter(Context context, int textViewResourceId,
				ArrayList<HashMap<String, String>> _items) {
			super(context, textViewResourceId, _items);
			this.items = _items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.row, null);
			} 
			v.setPadding(8, 8, 8, 8);

			
			HashMap<String, String> o = items.get(position);

			ImageView v_icon = (ImageView) v.findViewById(R.id.icon);
			if(v_icon != null) {
				Bitmap myBitmap = BitmapFactory.decodeFile(getFileStreamPath(o.get("title") + ".png").getAbsolutePath());
				if(myBitmap != null) {
					v_icon.setImageBitmap(myBitmap);
				}
			}
			if (o != null) {
				TextView tt = (TextView) v.findViewById(R.id.toptext);
				TextView bt = (TextView) v.findViewById(R.id.bottomtext);
				TextView rt = (TextView) v.findViewById(R.id.righttext);
				if (tt != null) {
					tt.setText(o.get("title"));
				}
				if (bt != null) {
					bt.setText(o.get("comment"));
				}
				if (rt != null) {
					if(CheckPackage(o.get("packageName"))) {
						rt.setText("설치됨");
					} else {
						rt.setText("미설치");
					}
				}
			}
			return v;
		}
	}


	public void setItemAdapter(ArrayList<HashMap<String, String>> itemArray) {
		m_adapter = new ItemAdapter(this, R.layout.row, itemArray);
		setListAdapter(m_adapter);
	}

}
